package com.ddd.config;

import com.ddd.core.filter.XssContentCacheFilter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.BaseHibernateValidatorConfiguration;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.validation.MessageInterpolatorFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.servlet.DispatcherType;

/**
 * @Author: zhongwenbin
 * @Date: 2023/6/28 11:02
 **/
@Slf4j
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(DDDProperties.class)
public class CommonAutoConfiguration {

    private final DDDProperties dddProperties;

    /**
     * 注册filter
     */
    @Bean
    @Lazy(value = false)
    @SuppressWarnings({"rawtypes", "unchecked"})
    public FilterRegistrationBean getfilterRegistrationBean() {
        log.info("xss 过滤器注入bean开启");
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setDispatcherTypes(DispatcherType.REQUEST);
        bean.setFilter(new XssContentCacheFilter());
        bean.setName("contentCacheFile");
        bean.addUrlPatterns("/*");
        bean.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        String xsslExcludes = dddProperties.getXsslExcludes();
        bean.addInitParameter("excludes", xsslExcludes == null ? "" : xsslExcludes);
        return bean;
    }

    /**
     * jar303效验快速失败
     */
    @Bean
    public LocalValidatorFactoryBean validator() {
        log.info("Hibernate Validator 开启快速失败");
        LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
        validatorFactoryBean.getValidationPropertyMap().put(BaseHibernateValidatorConfiguration.FAIL_FAST, "true");
        return validatorFactoryBean;
    }
}
